<template>
  <ElCard class="hfull p20px">
    <template #header>
      <div class="card-header">
        <span>新用户注册</span>
      </div>
    </template>
    <el-form label-position="right" label-width="100px" :model="data" class="p10">
      <el-form-item label="用户名">
        <el-input v-model="data.username" />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="data.name" />
      </el-form-item>
      <el-form-item label="密码">
        <InputPassword v-model="data.password" strength />
      </el-form-item>
      <el-form-item label="密码确认">
        <InputPassword v-model="passwordConfirm" strength />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex-center">
        <ElButton type="primary" @click="regist">注册</ElButton>
        <ElButton @click="login">返回登录</ElButton>
      </div>
    </template>
  </ElCard>
</template>
<script setup lang="ts">
  import { ElButton, ElInput, ElForm, ElFormItem, ElCard } from 'element-plus'
  import { reactive, ref } from 'vue'
  import { InputPassword } from '@/components/InputPassword'
  import { registApi } from '@/api'
  import fb from '@/utils/feedback'
  import { useRouter } from 'vue-router'

  const { replace } = useRouter()
  const passwordConfirm = ref<string>()
  const data = reactive({
    username: '',
    name: '',
    password: ''
  })

  const regist = async () => {
    if(!data.username) {
      fb.alertError('请填写用户名')
      return
    }
    if(!data.password) {
      fb.alertError('请填写密码')
      return
    }
    if(!passwordConfirm.value) {
      fb.alertError('请确认密码')
      return
    }
    if(data.password !== passwordConfirm.value) {
      fb.alertError('密码不一致')
      return
    }

    const res = await registApi(data)
    if(res) {
      replace('/login')
    } else {
      fb.alertError('注册失败')
    }
  }

  const login = () => replace('/login')
</script>